package xhwl.insurance.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.R;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.event.FreshForumListEvent;
import xhwl.insurance.event.FreshPicEvent;
import xhwl.insurance.http.api.SendForumApi;
import xhwl.insurance.http.api.UploadPicApi;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.morepic.adapter.ImagePutQuestionsPublishAdapter;
import xhwl.insurance.morepic.adapter.util.CustomConstants;
import xhwl.insurance.morepic.adapter.util.IntentConstants;
import xhwl.insurance.morepic.adapter.view.ImageZoomActivity;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by Administrator on 2017/9/28.
 * 论坛提问页面
 */

public class PutQuestionsActivity extends BaseActivity implements View.OnClickListener, PopSelectPic.PopSelectBtnClickListener {
    //    private static String[] PERMISSION = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final String TAG = PutQuestionsActivity.class.getSimpleName();
    private static final int REQUEST_CODE_VIEW_PIC = 0x000001;
    private static final int TAKE_PICTURE = 0x000000;

    private GridView mGridView;
    private TextView mRemind;
    private EditText mEditTextTitle;
    private EditText mEditTextDetail;

    private ImagePutQuestionsPublishAdapter mAdapter;
    public List<ImageItem> mDataList = new ArrayList<ImageItem>();

    private String path = "";

    private String postTitle;
    private String postDetails;
    private TextView mEditTextNum;
    private ImageView mDelet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.question_activity);
    }

    @Override
    public void initViews() {
        initTitleViews();
        mEditTextTitle = (EditText) findViewById(R.id.et_title);
        mEditTextDetail = (EditText) findViewById(R.id.et_detail);
        mRemind = (TextView) findViewById(R.id.tv_remind);
        mGridView = (GridView) findViewById(R.id.gridview);
        mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));

        mAdapter = new ImagePutQuestionsPublishAdapter(this, mDataList);
        mGridView.setAdapter(mAdapter);
        //当前输入的字数
        mEditTextNum = (TextView) findViewById(R.id.tv_num);

    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        titleTextView.setText("提问");
        rightTextView.setVisibility(View.VISIBLE);
        rightTextView.setText("发表");
    }

    @Override
    public void initListener() {
        rightTextView.setOnClickListener(this);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == mDataList.size()) {
                    PopSelectPic popfront = new PopSelectPic(PutQuestionsActivity.this, mGridView);
                    popfront.setCallBack(PutQuestionsActivity.this);
                } else {
//                    Intent intent = new Intent(PutQuestionsActivity.this, ImageZoomActivity.class);
//                    intent.putExtra(IntentConstants.EXTRA_IMAGE, mDataList.get(position));
//                    intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
//                    startActivityForResult(intent,REQUEST_CODE_VIEW_PIC);

                }
            }
        });
        mEditTextTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 20) { //判断EditText中输入的字符数是不是已经大于20
                    mEditTextTitle.setText(s.toString().substring(0, 20)); //设置EditText只显示前面20位字符
                    mEditTextTitle.setSelection(20);//让光标移至末端
                    Toast.makeText(PutQuestionsActivity.this, "标题过长", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mEditTextDetail.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = s.length();
                mEditTextNum.setText("" + number);
                if (temp.length() > 140) {
                    mEditTextDetail.setText(s.toString().substring(0, 140));
                    mEditTextDetail.setSelection(140);
                    Toast.makeText(PutQuestionsActivity.this, "内容过长", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });

    }

    @Override
    public void loadData() {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_right_textview:
                show();
//                if (mDataList.size()==0){
//                    SendForums("");
//                }else{
//                    List<File> list=new ArrayList<>();
//                    for(ImageItem item:mDataList){
//                        File file=new File(item.getSourcePath());
//                        if(file!=null&&file.exists()){
//                            list.add(file);
//                        }
//                    }
//                    uploadPic(list);
//                }

                break;

            default:
                break;
        }

    }

    private void show() {
        AlertDialog builder = new AlertDialog.Builder(PutQuestionsActivity.this)
                .setMessage("确认发表吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mDataList.size() == 0) {
                            SendForums("");
                        } else {
                            List<File> list = new ArrayList<>();
                            for (ImageItem item : mDataList) {
                                File file = new File(item.getSourcePath());
                                if (file != null && file.exists()) {
                                    list.add(file);
                                }
                            }
                            uploadPic(list);
                        }
                        dialog.dismiss();

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();


                    }
                }).create();
        builder.show();
    }

    private void uploadPic(final List<File> fileList) {
        if (fileList == null || fileList.size() == 0)
            return;

        final UploadPicApi api = new UploadPicApi(mContext, true, fileList.toArray(new File[fileList.size()]));
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();

            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                api.hideDialog();
                StringBuilder sb = new StringBuilder();
                for (ReferralPicBean bean : picBeanList) {
                    sb.append(bean.getUrl_big()).append(";");
                }
                SendForums(sb.toString());
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                api.hideDialog();
            }
        });
    }

    /**
     * 不带图片时发表论坛
     */
    private void SendForums(String post_urls) {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        postTitle = mEditTextTitle.getText().toString().trim();
        postDetails = mEditTextDetail.getText().toString().trim();
//        String post_type = StringUtil.isEmpty(post_urls) ? "0" : "0";
        BaseApi api = new SendForumApi(member_id, postTitle, post_urls, postDetails, "0","");
        HttpManager.getInstance().dealHttp(PutQuestionsActivity.this, api, new OnNextListener<HttpResp>() {

            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    ToastUtil.showToast(PutQuestionsActivity.this, "发表成功");
                    EventBus.getDefault().post(new FreshForumListEvent());
                    finish();
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }

        });
    }

    //图片处理开始
    private int getAvailableSize() {
        int availSize = CustomConstants.MAX_IMAGE_SIZE - mDataList.size();
        if (availSize >= 0) {
            return availSize;
        }
        return 0;
    }

    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
//        if (PermisionUtils.islacksOfPermission(this, PERMISSION[1])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将无法选择您的照片");
//            ActivityCompat.requestPermissions(this, PERMISSION, 1);
//        } else {
//            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
//            intent.putExtra(xhwl.insurance.util.IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
//            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
//            startActivity(intent);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestPermission();
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                    intent.putExtra(xhwl.insurance.util.IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
                    startActivity(intent);
                } else {
                    Log.e(TAG, "用户拒绝开启权限");
                    PermisionUtils.dialog(PutQuestionsActivity.this, "用户拒绝开启权限");
                }
            }
        });


    }


    public void takePhoto() {
//        if (PermisionUtils.islacksOfPermission(mContext, PERMISSION[0])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将影响拍照功能无法使用");
//            ActivityCompat.requestPermissions(this, PERMISSION, 0);
//        } else {
//            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//            File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
//            if (!vFile.exists()) {
//                File vDirPath = vFile.getParentFile();
//                vDirPath.mkdirs();
//            } else {
//                if (vFile.exists()) {
//                    vFile.delete();
//                }
//            }
//            path = vFile.getPath();
//            Uri cameraUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                cameraUri = FileProvider.getUriForFile(this.getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
//            } else {
//                cameraUri = Uri.fromFile(vFile);
//            }
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
//            startActivityForResult(openCameraIntent, TAKE_PICTURE);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestTakePicPermission();
    }

    private void requestTakePicPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(PutQuestionsActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }

    public void onEvent(FreshPicEvent event) {
        mAdapter.notifyDataSetChanged();
        if (mDataList.size() == 0) {
            mRemind.setVisibility(View.VISIBLE);
        } else {
            mRemind.setVisibility(View.GONE);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                ImageItem item = new ImageItem();
                item.sourcePath = path;
                XHLog.e("sourcePath=" + item.sourcePath);
                initImageFiles(item);
            }
            //处理删除图片逻辑
            else if (requestCode == REQUEST_CODE_VIEW_PIC) {
                if (data != null) {
                    int delPos = data.getIntExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, 0);
                    mDataList.remove(delPos);
                    notifyDataChanged();
                }
            }
        }

    }

    private void initImageFiles(ImageItem item) {
        String fileName = xhwl.insurance.util.BitmapUtil.handleImage(mContext, item.sourcePath, 200);
        File file = new File(fileName);
        mDataList.add(item);
        notifyDataChanged();

    }

    //图片处理结束
    private void notifyDataChanged() {
        if (mDataList.size() != 0) {
            mRemind.setVisibility(View.GONE);
        } else {
            mRemind.setVisibility(View.VISIBLE);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
